package com.atlin.project.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.atlin.project.config.AliPayConfig;
import com.atlin.project.model.enums.biProduces.BiProductsOrderStatusEnum;
import com.atlin.project.service.BiProductsOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author atlin
 * @description
 * @createDate 2024/11/25 22:32
 */
@RestController
@RequestMapping("/pay")
@Slf4j
public class AlipayController {

    @Resource
    private BiProductsOrderService biProductsOrderService;

    @PostMapping("/notification")
    public void doNotification(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            params.put(key, value);
        }

        try {
            // 验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAYPUBLICKEY, "UTF-8", "RSA2");
            if (signVerified) {
                // 签名验证通过
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    // 支付成功
                    String outTradeNo = params.get("out_trade_no");
                    String tradeNo = params.get("trade_no");
                    String totalAmount = params.get("total_amount");
                    
                    log.info("支付成功 商户订单号:{},支付宝流水号:{},交易金额:{}", outTradeNo, tradeNo, totalAmount);
                    // 响应支付宝通知处理成功
                    biProductsOrderService.paymentHandle(Long.valueOf(outTradeNo), tradeNo, BiProductsOrderStatusEnum.HAVE_PAID);
                    
                    response.getWriter().write("success");
                } else {
                    // 支付失败或其他状态
                    // TODO: 处理其他状态
                    log.error("支付失败");
                }
            } else {
                // 签名验证失败
                // TODO: 记录日志或处理异常情况
                log.error("签名验证失败");
            }
        } catch (Exception e) {
            log.error("发生异常", e);
            // 异常处理
        }

    }
}
